<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <h2>深浅拷拷贝</h2>
</body>
<script>
    //1.浅拷贝
    const obj = {
        name: 'alice',
        age: 20,
        u: undefined,
        fn: function() {},
        hobby: ['打球', '游泳']
    }

    // const obj2 = Object.assign({}, obj)
    // const obj2 = {...obj}
    // obj2.name = '张三'
    //  obj2.hobby[0] = '跑步666'

    // console.log(obj)
    // console.log(obj2)

    //2.深拷贝
    // const obj2 = JSON.parse(JSON.stringify(obj))

    // obj.hobby[0] = '跑步888'

    // console.log(obj)
    // console.log(obj2)

    //递归实现深拷贝
    function cloneDeep(target) {
        if (typeof target !== 'object') return;
        let result = Array.isArray(target) ? [] : {}

        for (let key in target) {
            result[key] = typeof target[key] === 'object' ? cloneDeep(target[key]) : target[key]
        }

        return result;

    }


    const res1 = cloneDeep(obj)

    res1.hobby[1] = '健身'

    console.log('obj:', obj)
    console.log('res1:', res1)
</script>

</html>